import Foundation
import SwiftyUserDefaults
import SwiftyJSON
import Alamofire
import AlamofireImage

private var userInfo = UserInfo()

class UserInfo: NSObject {
    
    @objc var token: String = ""
    @objc var userId: String = ""
    @objc var userName: String = ""
    @objc var userAvatar: String = ""
    @objc var userAccount: String = ""
    @objc var preUserAccount: String = ""
    
    //MARK: - 单例
    class var sharedInstance: UserInfo {
        let userInfoDic = Defaults.defaults.dictionary(forKey: "UserInfo")
        if userInfoDic != nil{
            userInfo =  UserInfo.mj_object(withKeyValues: userInfoDic)
        }
        return userInfo
    }
    
    //MARK: - 登录
    func toLogin(_ way: String, _ qrcode: String? = "") {
        var model:TXCustomModel = TXCustomModel.init()
        if way == "normal" {
            model = PNSBuildModelUtils.buildFullScreenModel()
            model.supportedInterfaceOrientations = .portrait
            model.presentDirection = .right
        } else if way == "tv" {
            model = PNSBuildModelUtilsTV.buildFullScreenModel(qrcode!)
            model.supportedInterfaceOrientations = .portrait
            model.presentDirection = .right
        }
        
        // 调用check接口检查及准备接口调用环境
        TXCommonHandler.sharedInstance().checkEnvAvailable(with: .loginToken) { (resultDic) in
            if PNSCodeSuccess.isEqual(resultDic?["resultCode"]) == false {
                print("一键登录：环境不支持")
                NotificationCenter.default.post(name: NSNotification.Name(AppConfig.sharedInstance.AuthPageFunctionNotification), object: [
                    "action": "OtherLoginWay",
                    "qrcode": "",
                    "pageFrom": "normal"
                ])
                return
            }
            
            // 调用取号接口，加速授权页的弹起
            TXCommonHandler.sharedInstance().accelerateLoginPage(withTimeout: 3) { resultDic in
                if PNSCodeSuccess.isEqual(resultDic["resultCode"]) == false {
                    return
                }
                
                // 调用获取登录Token接口，可以立马弹起授权页
                TXCommonHandler.sharedInstance().getLoginToken(withTimeout: 3, controller: UtilManager.sharedInstance.getCurrentVc(), model: model) { resultDic in
                    let code = resultDic["resultCode"] as? String
                        if PNSCodeLoginControllerPresentSuccess.isEqual(code) {
                            print("一键登录：弹起授权页成功")
                        } else if PNSCodeLoginControllerClickCancel.isEqual(code) {
                            print("一键登录：点击了授权页的返回")
                        } else if PNSCodeLoginControllerClickChangeBtn.isEqual(code) {
                            print("一键登录：点击切换其他登录方式按钮")
                        } else if PNSCodeLoginControllerClickLoginBtn.isEqual(code) {
                            if (resultDic["isChecked"] as? NSNumber)?.boolValue ?? false == true {
                                print("一键登录：点击了登录按钮，check box选中，SDK内部接着会去获取登陆Token")
                            } else {
                                print("一键登录：点击了登录按钮，check box未选中，SDK内部不会去获取登陆Token")
                                UtilManager.sharedInstance.getCurrentVc().view.makeToast("请阅读并同意相关协议", duration: 1.0, position: .center)
                            }
                        } else if PNSCodeLoginControllerClickCheckBoxBtn.isEqual(code) {
                            print("一键登录：点击check box")
                        } else if (PNSCodeLoginControllerClickProtocol == code) {
                            print("一键登录：点击了协议富文本")
                        } else if PNSCodeSuccess.isEqual(code) {
                            //点击登录按钮获取登录Token成功回调
                            let token = resultDic["token"] as! String
                            print("一键登录token：\(String(describing: token))")
//                            UIPasteboard.general.string = "\(String(describing: token))"
                            
                            if way == "normal" {
                                var params = JSON.init(parseJSON: "{}")
                                params["token"].string = token
                                
                                APIManager.sharedInstance.sendRequest(urlString: APIManager.sharedInstance.at_auth_action, method: HTTPMethod.post, params: params) { (result, error) in
                                    
                                    if error == nil {
                                        var newData:[String:Any] = [:]
                                        newData["token"] = result["data"].dictionaryObject?["token"]
                                        UserInfo.sharedInstance.save(dic: newData)

                                        self.handleGetUserInfo()
                                    }
                                }
                            } else if way == "tv" {
                                var params = JSON.init(parseJSON: "{}")
                                params["qrcode"].string = qrcode
                                params["token"].string = token
                                
                                APIManager.sharedInstance.sendRequest(urlString: APIManager.sharedInstance.at_auth_tv_action, method: HTTPMethod.post, params: params) { (result, error) in
                                    
                                    if error == nil {
                                        UtilManager.sharedInstance.getCurrentVc().view.makeToast("登录成功", duration: 1.0, position: .center)
                                        DispatchQueue.main.asyncAfter(deadline: .now()+1) {
                                            TXCommonHandler.sharedInstance().cancelLoginVC(animated: false, complete: nil)
                                            UserInfo.sharedInstance.toLogin("normal")
                                        }
                                    }
                                }
                            }
                        } else {
                            UtilManager.sharedInstance.getCurrentVc().view.makeToast("获取登录Token失败", duration: 1.0, position: .center)
                            print("一键登录：获取登录Token失败")
                        }
                }
                
            }
        }
    }
    
    func handleGetUserInfo() {
        UtilManager.sharedInstance.showHud()
        
        let params = JSON.init(parseJSON: "{}")
        APIManager.sharedInstance.sendRequest(urlString: APIManager.sharedInstance.user_info_action, method: HTTPMethod.get, params: params) { (result, error) in
            if error == nil {
                UtilManager.sharedInstance.hideHud()
                
                var newData:[String:Any] = [:]
                newData["userId"] = result["data"].dictionaryObject?["userId"]
                newData["userAccount"] = result["data"]["accounts"]["attrs"].dictionaryObject?["mobile"]
                newData["userName"] = result["data"]["accounts"]["attrs"].dictionaryObject?["name"]
                newData["userAvatar"] = result["data"]["accounts"]["attrs"].dictionaryObject?["avatar"]
                UserInfo.sharedInstance.save(dic: newData)

                DispatchQueue.main.asyncAfter(deadline: .now()) {
                    TXCommonHandler.sharedInstance().cancelLoginVC(animated: false, complete: nil)
                }
                
                NotificationCenter.default.post(name: NSNotification.Name(AppConfig.sharedInstance.LoginNotification), object: self, userInfo: ["isLogin":UserInfo.sharedInstance.isLogin()])
            }
        }
    }
    
    func clearUserAutoLoginKey() {
        self.save(dic: nil)
    }
    
    func isLogin() -> Bool {
        return self.token != ""
    }
    
    func save(dic:[String: Any]?) {
        var mutableDic = dic
        
        if mutableDic == nil {
            self.token = ""
            self.userId = ""
            self.userName = ""
            self.userAvatar = ""
            self.userAccount = ""
        }
        else {
            for key in Array(mutableDic!.keys) {
                if self.mj_keyValues().object(forKey: key) == nil {
                    mutableDic!.removeValue(forKey: key)
                }
                else {
                    if mutableDic![key] is NSNumber {
                        if mutableDic![key] is Int64 {
                            mutableDic![key]=NSNumber(integerLiteral: mutableDic![key] as! Int).stringValue
                        }
                        else {
                            mutableDic![key]=NSNumber(floatLiteral: mutableDic![key] as! Double).stringValue
                        }
                        
                    }
                }
            }
            self.setValuesForKeys(mutableDic!)
        }
        
        Defaults.defaults.set(self.mj_keyValues(), forKey: "UserInfo")
        Defaults.defaults.synchronize()
    }
}

